package com.ruoyi.farmer.service.impl;

import com.agri.api.service.farmer.IFarmerProductsService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.model.farmer.domain.*;
import com.ruoyi.common.model.farmer.dto.req.FarmerProductsAddReq;
import com.ruoyi.common.model.farmer.dto.req.FarmerProductsReq;
import com.ruoyi.common.model.farmer.dto.resp.FarmerProductsCardResp;
import com.ruoyi.common.model.farmer.dto.resp.FarmerProductsResp;
import com.ruoyi.common.model.mall.dto.req.GoodListReq;
import com.ruoyi.common.model.mall.dto.resp.GoodSimpleItemResp;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ListUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;

import com.ruoyi.farmer.mapper.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

/**
 * @author huixh
 */
@Service
public class FarmerProductsServiceImpl implements IFarmerProductsService {

    @Resource
    private FarmerProductsMapper farmerProductsMapper;

    @Resource
    private FarmerProductsTagsMapperExt farmerProductsTagsMapperExt;

    @Resource
    private FarmerProductSpecificationsMapper farmerProductSpecificationsMapper;

    @Resource
    private FarmerProductSpecValueMapper farmerProductSpecValueMapper;

    @Resource
    private FarmerProductSkusMapper farmerProductSkusMapper;

    @Resource
    private FarmerTagsMapper farmerTagsMapper;

    @Resource
    private FarmerProductsImagesMapper farmerProductsImagesMapper;


    @Override
    public FarmerProductsResp selectFarmerProductsDetailById(Long id) {
        FarmerProducts products = farmerProductsMapper.selectFarmerProductsById(id);
        if (products == null) {
            throw new ServiceException("商品不存在", 500);
        }

        FarmerProductsResp farmerProductsResp = new FarmerProductsResp();
        BeanUtils.copyBeanProp(farmerProductsResp, products);

        // 设置商品图片
        List<FarmerProductsCardResp.Image> imagesList = farmerProductsImagesMapper
                .selectProductsImagesByPid(products.getId())
                .stream()
                .map(img -> {
                    FarmerProductsCardResp.Image image = new FarmerProductsCardResp.Image();
                    image.setUrl(img.getImageUrl());
                    return image;
                }).collect(Collectors.toList());
        farmerProductsResp.setImages(imagesList);

        // 设置产地
        farmerProductsResp.setOrigin(ListUtils.stringToList(products.getOrigin()));

        // 设置规格和规格值
        List<FarmerProductSpecification> productSpecifications = farmerProductSpecificationsMapper.selectProductSpecificationsByProductId(id);
        Map<Long, List<FarmerProductSpecValue>> specValuesBySpecId = fetchSpecValuesBySpecId(productSpecifications);
        farmerProductsResp.setSpecifications(buildSpecifications(productSpecifications, specValuesBySpecId));

        // 设置 SKU
        List<FarmerProductsCardResp.Sku> skuList = farmerProductSkusMapper
                .selectSkusByProductId(id)
                .stream()
                .map(this::buildSku)
                .collect(Collectors.toList());
        farmerProductsResp.setSkus(skuList);

        return farmerProductsResp;
    }

    private Map<Long, List<FarmerProductSpecValue>> fetchSpecValuesBySpecId(List<FarmerProductSpecification> specifications) {
        List<Long> specIds = specifications.stream()
                .map(FarmerProductSpecification::getId)
                .collect(Collectors.toList());
        return farmerProductSpecValueMapper
                .selectSpecValueBySpecIds(specIds)
                .stream()
                .collect(Collectors.groupingBy(FarmerProductSpecValue::getSpecificationId));
    }

    private List<FarmerProductsCardResp.Specification> buildSpecifications(
            List<FarmerProductSpecification> specifications,
            Map<Long, List<FarmerProductSpecValue>> specValuesBySpecId) {
        return specifications.stream().map(spec -> {
            FarmerProductsCardResp.Specification specification = new FarmerProductsCardResp.Specification();
            specification.setId(spec.getId().intValue());
            specification.setName(spec.getName());
            List<String> values = specValuesBySpecId.getOrDefault(spec.getId(), Collections.emptyList())
                    .stream()
                    .map(FarmerProductSpecValue::getSpecificationValue)
                    .collect(Collectors.toList());
            specification.setValues(values);
            return specification;
        }).collect(Collectors.toList());
    }

    private FarmerProductsCardResp.Sku buildSku(FarmerProductSkus sku) {
        FarmerProductsCardResp.Sku skuResp = new FarmerProductsCardResp.Sku();
        skuResp.setId(sku.getId().intValue());
        skuResp.setPrice(sku.getPrice().doubleValue());
        skuResp.setStock(Math.toIntExact(sku.getStock()));
        skuResp.setImage(sku.getMainImage());
        skuResp.setSpecs(new FarmerProductsCardResp.Sku.Specs());
        return skuResp;
    }

    @Override
    public List<FarmerProductsCardResp> selectFarmerProductsList(FarmerProducts farmerProducts) {
        PageUtils.startPage();
        List<FarmerProducts> farmerProductsList = farmerProductsMapper.selectFarmerProductsList(farmerProducts);
        PageUtils.clearPage();

        if (farmerProductsList.isEmpty()) {
            return Collections.emptyList(); // 无数据直接返回
        }

        List<Long> productIds = farmerProductsList.stream().map(FarmerProducts::getId).collect(Collectors.toList());

        // 查询规格和规格值
        Map<Long, List<FarmerProductSpecification>> specificationsByProductId = fetchSpecificationsByProductId(productIds);
        Map<Long, List<FarmerProductSpecValue>> specValuesBySpecId = fetchSpecValuesBySpecId(
                specificationsByProductId.values().stream().flatMap(List::stream).collect(Collectors.toList())
        );

        // 查询 SKU
        Map<Long, List<FarmerProductSkus>> skusByProductId = farmerProductSkusMapper.selectSkusByProductIds(productIds)
                .stream()
                .collect(Collectors.groupingBy(FarmerProductSkus::getProductId));

        // 构建响应
        return farmerProductsList.stream().map(product -> {
            FarmerProductsCardResp resp = new FarmerProductsCardResp();
            BeanUtils.copyBeanProp(resp, product);

            // 设置规格
            List<FarmerProductSpecification> specifications = specificationsByProductId.getOrDefault(product.getId(), Collections.emptyList());
            resp.setSpecifications(buildSpecifications(specifications, specValuesBySpecId));

            // 设置 SKU
            List<FarmerProductsCardResp.Sku> skus = skusByProductId.getOrDefault(product.getId(), Collections.emptyList())
                    .stream()
                    .map(this::buildSku)
                    .collect(Collectors.toList());
            resp.setSkus(skus);

            return resp;
        }).collect(Collectors.toList());
    }

    private Map<Long, List<FarmerProductSpecification>> fetchSpecificationsByProductId(List<Long> productIds) {
        return farmerProductSpecificationsMapper
                .selectProductSpecificationsByProductIds(productIds)
                .stream()
                .collect(Collectors.groupingBy(FarmerProductSpecification::getProductId));
    }


    /**
     * 新增products
     *
     * @param farmerProducts products
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertFarmerProducts(FarmerProductsAddReq farmerProducts)
    {

        // Step 1: 插入 farmer_products 表
        FarmerProducts product = new FarmerProducts();
        product.setProductsName(farmerProducts.getProductsName());
        product.setCategoryId(farmerProducts.getCategoryId());
        product.setStatus(farmerProducts.getStatus());
        product.setStorageCondition(farmerProducts.getStorageCondition());
        product.setShelfLife(farmerProducts.getShelfLife());
        String origin = farmerProducts.getOrigin().stream().map(String::valueOf).collect(Collectors.joining(","));
        product.setOrigin(origin); // 地区
        product.setDescription(farmerProducts.getDescription());
        product.setMainImage(farmerProducts.getMainImage());
        product.setCreateTime(new Date());
        product.setUpdateTime(new Date());
        product.setCreateBy("System"); // todo 可动态获取
        product.setUpdateBy("System"); // todo 可动态获取

        farmerProductsMapper.insertFarmerProducts(product);
        Long productId = product.getId(); // 获取插入后返回的主键

        // Step 2: 插入 product_specifications 表
        List<FarmerProductSpecification> specifications = new ArrayList<>();
        for (FarmerProductsAddReq.Specification spec : farmerProducts.getSpecifications()) {
            FarmerProductSpecification specification = new FarmerProductSpecification();
            specification.setProductId(productId);
            specification.setName(spec.getName());
            specification.setCreateTime(new Date());
            specification.setUpdateTime(new Date());
            specifications.add(specification);
        }
        if (!specifications.isEmpty()) {
            farmerProductSpecificationsMapper.batchInsert(specifications); // 批量插入
        }

        // 获取规格 ID 对应的 Map，用于后续插入规格值
        Map<String, Long> specNameToIdMap = specifications.stream()
                .collect(Collectors.toMap(FarmerProductSpecification::getName, FarmerProductSpecification::getId));

        // Step 3: 插入 product_spec_values 表
        List<FarmerProductSpecValue> specValues = new ArrayList<>();
        for (FarmerProductsAddReq.Specification spec : farmerProducts.getSpecifications()) {
            Long specId = specNameToIdMap.get(spec.getName());
            for (String value : spec.getValues()) {
                FarmerProductSpecValue specValue = new FarmerProductSpecValue();
                specValue.setSpecificationId(specId);
                specValue.setSpecificationValue(value);
                specValue.setCreateTime(new Date());
                specValue.setUpdateTime(new Date());
                specValues.add(specValue);
            }
        }
        if (!specValues.isEmpty()) {
            farmerProductSpecValueMapper.batchInsert(specValues); // 批量插入
        }

        // Step 4: 插入 product_skus 表
        List<FarmerProductSkus> skus = new ArrayList<>();
        for (FarmerProductsAddReq.Sku skuReq : farmerProducts.getSkuList()) {
            FarmerProductSkus sku = new FarmerProductSkus();
            sku.setProductId(productId);
            sku.setPrice(BigDecimal.valueOf(skuReq.getPrice()));
            sku.setStock(skuReq.getStock());
            sku.setMainImage(skuReq.getImage());

            // 拼接规格与规格值
            List<String> skuSpecValues = new ArrayList<>();
            for (FarmerProductsAddReq.Sku.Spec spec : skuReq.getSpecs()) {
                skuSpecValues.add(spec.getName() + ":" + spec.getValue());
            }
            sku.setSpecValueIds(String.join(",", skuSpecValues)); // 存储为 "内存:16,颜色:深空灰" 格式

            sku.setCreateTime(new Date());
            sku.setUpdateTime(new Date());
            skus.add(sku);
        }
        if (!skus.isEmpty()) {
            farmerProductSkusMapper.batchInsert(skus); // 批量插入
        }
    }

    /**
     * 修改products
     *
     * @param id
     * @param farmerProducts products
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateFarmerProducts(Long id, FarmerProductsAddReq farmerProducts)
    {
        // todo 这里布隆过滤器过滤下
        FarmerProducts products = new FarmerProducts();
        BeanUtils.copyBeanProp(products, farmerProducts);
        String originStr = farmerProducts.getOrigin().stream().map(String::valueOf).collect(Collectors.joining(","));
        products.setOrigin(originStr);
        products.setUpdateTime(DateUtils.getNowDate());
        products.setUpdateBy(SecurityUtils.getUsername());
        farmerProductsMapper.updateFarmerProducts(products);
        farmerProductsImagesMapper.deleteProductsImagesByPid(new Long[]{id});
        AtomicLong imageIndex = new AtomicLong(0L);
        List<FarmerProductsImages> productsImages = farmerProducts.getImages().stream().map(image -> {
            FarmerProductsImages farmerProductsImages = new FarmerProductsImages();
            farmerProductsImages.setProductId(id);
            farmerProductsImages.setImageUrl(image.getUrl());
            farmerProductsImages.setImageOrder(imageIndex.get());
            imageIndex.getAndIncrement();
            return farmerProductsImages;
        }).collect(Collectors.toList());
        farmerProductsImagesMapper.insertProductsImages(productsImages);
        products.setId(id);
        farmerProductsMapper.updateFarmerProducts(products);
    }

    /**
     * 批量删除products
     *
     * @param ids 需要删除的products主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteFarmerProductsByIds(Long[] ids)
    {
        // 清空关联图片
        farmerProductsImagesMapper.deleteProductsImagesByPid(ids);
        // 清楚关联 标签关联信息
        farmerProductsTagsMapperExt.deleteProductsTagsByPid(ids);
        return farmerProductsMapper.deleteFarmerProductsByIds(ids);
    }

    /**
     * 删除products信息
     *
     * @param id products主键
     * @return 结果
     */
    @Override
    public int deleteFarmerProductsById(Long id)
    {
        return farmerProductsMapper.deleteFarmerProductsById(id);
    }

    /**
     * 插入products 详细信息
     *
     * @param farmerProducts@return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertFarmerProductsInfo(FarmerProductsReq farmerProducts) {

        FarmerProducts products = new FarmerProducts();
        BeanUtils.copyBeanProp(products, farmerProducts);
        List<Long> origin = farmerProducts.getOrigin();
        String originStr = ListUtils.listToString(origin);
        products.setOrigin(originStr);
        products.setCreateTime(DateUtils.getNowDate());
        String username = SecurityUtils.getUsername();
        products.setCreateBy(username);
        farmerProductsMapper.insertFarmerProducts(products);
        Long productsId = products.getId();
        List<Long> features = farmerProducts.getFeatures();
        farmerProductsTagsMapperExt.insertProductsTags(productsId, features);
        List<FarmerProductsImages> images = farmerProducts.getImages();

        for (int i = 0; i < images.size(); i++) {
            FarmerProductsImages item = images.get(i);
            item.setProductId(productsId);
            item.setImageOrder((long) i);
            item.setIsPrimary("false");
        }
        farmerProductsImagesMapper.insertProductsImages(images);

    }

    /**
     * 根据分类ID 查询商品列表
     *
     * @param goodListReq goodListReq
     * @return list
     */
    @Override
    public List<GoodSimpleItemResp> selectGoodsListByCategoryId(GoodListReq goodListReq) {
        Integer categoryId = goodListReq.getType();
        PageUtils.startPage(goodListReq.getPageNum(), goodListReq.getPageSize(), true);
        PageUtils.orderBy(goodListReq.getSortField() + " " + goodListReq.getSortType());
        List<GoodSimpleItemResp> simpleItemResps = farmerProductsMapper.selectFarmerProductsByCategoryId(Long.valueOf(categoryId));
        PageUtils.clearPage();
        return simpleItemResps;
    }
}
